import requests
import time
import hashlib
from notify import send  # 青龙通知模块
##cron: 36 9 * * *
##new Env("人民出行")

def generate_sign(params, secret_key=None):
    """生成签名（示例算法，实际需要根据接口规则调整）"""
    # 这里只是一个示例，实际签名算法需要根据接口文档实现
    param_str = '&'.join([f'{k}={v}' for k, v in sorted(params.items())])
    if secret_key:
        param_str += secret_key
    return hashlib.md5(param_str.encode('utf-8')).hexdigest()

def baojia_sign(user_id, token, ad_code="440500", latitude=23.39380642, longitude=116.73050890):
    """人民出行签到函数"""
    
    # 基础URL和headers
    url = "https://me.baojia.com/bike/activity/sign/data"
    headers = {
        "Host": "me.baojia.com",
        "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.136 Mobile Safari/537.36 XWEB/1340129 MMWEBSDK/20221011 MMWEBID/9222 MicroMessenger/8.0.30.2260(0x28001E3B) WeChat/arm64 Weixin NetType/4G Language/zh_CN ABI/arm64 miniProgram/wxec491985214cc7fc",
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundarytWau5hpeBL7f4dSe",
        "Referer": "https://static.meboth.cn/",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }
    
    # 准备请求参数
    timestamp = str(int(time.time() * 1000))
    params = {
        "timestamp": timestamp,
        "userId": user_id,
        "adCode": ad_code,
        "appFrom": "15",
        "deviceType": "2",
        "mobileLatitude": str(latitude),
        "mobileLongitude": str(longitude),
        "appVersion": "7.1.8",
        "token": token
    }
    
    # 生成签名（需要根据实际接口规则调整）
    sign = generate_sign(params)
    params["sign"] = sign
    
    # 构建multipart/form-data格式的请求体
    boundary = "----WebKitFormBoundarytWau5hpeBL7f4dSe"
    data_lines = []
    for key, value in params.items():
        data_lines.append(f'--{boundary}')
        data_lines.append(f'Content-Disposition: form-data; name="{key}"')
        data_lines.append('')
        data_lines.append(str(value))
    data_lines.append(f'--{boundary}--')
    data_lines.append('')
    data = '\r\n'.join(data_lines)
    
    try:
        # 发送请求
        response = requests.post(url, headers=headers, data=data)
        response.raise_for_status()  # 检查HTTP错误
        
        result = response.json()
        
        # 解析结果
        if result.get("code") == 200:
            msg = "✅ 人民出行签到成功！\n"
            msg += f"📅 本月已签到: {result['data']['signedCount']}天\n"
            
            # 检查今日是否已签到
            today = time.strftime("%Y-%m-%d")
            for day in result["data"]["dayList"]:
                if day["curDay"].startswith(today):
                    if day["signStatus"] == 1:
                        msg += "🎉 今日签到状态: 已签到\n"
                    else:
                        msg += "⚠️ 今日签到状态: 未签到\n"
                    break
            
            # 获取签到二维码
            if "wxMiniAcodeUrl" in result["data"]:
                msg += f"📸 签到二维码: {result['data']['wxMiniAcodeUrl']}"
            
            return True, msg, result
        else:
            error_msg = f"❌ 人民出行签到失败: {result.get('message', '未知错误')}"
            return False, error_msg, result
            
    except requests.exceptions.RequestException as e:
        error_msg = f"❌ 人民出行请求出错: {str(e)}"
        return False, error_msg, {"error": str(e)}
    except ValueError as e:
        error_msg = f"❌ 人民出行响应解析出错: {str(e)}"
        return False, error_msg, {"error": "Invalid JSON response"}

# 配置区（请修改以下变量）
USER_CONFIG = {
    "user_id": "26501181",          # 替换为你的用户ID
    "token": "1GDKu9Lxciqh6DKM",    # 替换为你的token
    "ad_code": "440500",             # 地区编码（可选，默认440500）
    "latitude": 23.39380642,         # 纬度（可选）
    "longitude": 116.73050890        # 经度（可选）
}

# 使用示例
if __name__ == "__main__":
    # 执行签到
    success, message, result = baojia_sign(
        user_id=USER_CONFIG["user_id"],
        token=USER_CONFIG["token"],
        ad_code=USER_CONFIG["ad_code"],
        latitude=USER_CONFIG["latitude"],
        longitude=USER_CONFIG["longitude"]
    )
    
    # 打印结果到日志
    print(message)
    
    # 发送通知
    send("人民出行签到结果", message)
    
    # 返回结果给青龙面板
    if not success:
        exit(1)